import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:event_bus/event_bus.dart';

abstract class NetworkUtils {
  static ConnectivityResult preStatus = ConnectivityResult.none;

  static Future<List<ConnectivityResult>> getConnectStatus() async {
    return await Connectivity().checkConnectivity();
  }

  /// 无网络
  static Future<bool> isNone() async {
    return (await getConnectStatus()).contains(ConnectivityResult.none);
  }

  /// 移动网络
  static Future<bool> isMobile() async {
    return (await getConnectStatus()).contains(ConnectivityResult.mobile);
  }

  /// wifi网络
  static Future<bool> isWifi() async {
    return (await getConnectStatus()).contains(ConnectivityResult.wifi);
  }

  /// 网络切换到非wifi需要提示流量消耗
  static Future<bool> isShowToast() async {
    final status = await getConnectStatus();
    // 当网络状态切换之后 并且不是WiFi的时候提示为4G
    if (!status.contains(preStatus) &&
        !status.contains(ConnectivityResult.wifi)) {
      return Future.value(true);
    }
    return Future.value(false);
  }

  /// 有网/无网络 切换
  static Future<void> statusChanged(Function(bool) callback) async {
    Connectivity().onConnectivityChanged.listen((status) {
      if (status.contains(ConnectivityResult.none)) {
        callback(false);
      } else {
        callback(true);
      }
    });
  }
}

final eventBus = EventBus();
